﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Content.SiteMap;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:SiteMap runat=server></{0}:SiteMap>")]
    public class SiteMap : WebControl
    {

        private WebSiteMap map = null;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            map = new WebSiteMap(Content.Sites.SiteDefinition.GetCurrent(), true);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<ul id=\"" + this.ClientID + "\" ");
            if (!string.IsNullOrEmpty(this.CssClass)) { writer.Write("class=\"" + this.CssClass + "\""); }
            writer.Write(">");
            foreach (WebSiteMapNode node in map)
            {
                writer.Write("<li><a href=\"" + node.LocalUrl + "\">" + node.Title + "</a>");
                if (node.HasChildren) { RenderChildNodes(writer, node); }
                writer.Write("</li>");
            }

            writer.Write("</ul>");
        }

        private void RenderChildNodes(HtmlTextWriter writer, WebSiteMapNode parent)
        {
            writer.Write("<ul>");
            foreach (WebSiteMapNode node in parent.ChildNodes)
            {
                writer.Write("<li><a href=\"" + node.LocalUrl + "\">" + node.Title + "</a>");
                if (node.HasChildren)
                {
                    RenderChildNodes(writer, node);
                }
                writer.Write("</li>");
            }
            writer.Write("</ul>");
        }

    }
}
